<template>
  <n-card class="f-ad-creative-media ad-create-adv-position"
    :header-style="{ padding: '10px', background: '#F1F5FF', marginBottom: '10px' }" style="min-height: 317px;">
    <template #header> {{ index }}.广告版位</template>
    <n-skeleton :repeat="6" text v-if="position.loading"></n-skeleton>
    <n-empty description="请先至少选择一个账户" v-if="!account" style="margin-top: 40px">

    </n-empty>

    <div v-if="!position.loading && accounts.length">
      <n-radio-group v-model:value="position.siteSetType" :disabled="!account" @update:value="changeSiteType">
        <n-radio-button :value="2" label="2">特定版位</n-radio-button>
        <n-radio-button :value="1" label="1">自动版位</n-radio-button>
      </n-radio-group>
      <PositionSummary @update="onSitesitUpdate" :disabled="isSiteSetDisabled(item.id)" style="margin-top: 12px"
        v-for="item in formatTreeList" :key="item.code" :detail="item" :list="treeList" :select="select" />

      <div class="text-right mt-10" v-if="sitsetAutomaticRuleModal.length"> <span @click="handleModalShow"
          class="link-color cursor-pointer">版位定投</span></div>
      <!-- <div style="background-color: #FAFBFF;padding: 24px 16px;border-radius: 8px;">

      </div> -->
    </div>
    <n-modal v-model:show="modal.show" preset="card" title="版位定投场景" :bordered="false" :style="{ width: '980px' }">
      <n-scrollbar style="max-height: 500px;">
        <x-form ref="FormRef" v-model:model="modal.form" size="small" label-placement="left" label-width="200px">
          <n-form-item :label="sitset.name" path="title" v-for="sitset in sitsetAutomaticRuleModal" :key="sitset.code">
            <div class="flex-1">

              <n-radio-group style="height: 28px;line-height: 28px;"
                v-model:value="(modal.form as any)[sitset.key].type"
                @update:value="changeSceneCustome(sitset, (modal.form as any)[sitset.key].type)">
                <n-radio babel="NONE" value="NONE">不限</n-radio>
                <n-radio babel="CUSTOM" value="CUSTOM">自定义</n-radio>
              </n-radio-group>
              <div class="scene-custom-container"
                style="background-color: #fafafb;padding: 12px;margin-top: 20px;border-radius: 3px;"
                v-if="(modal.form as any)[sitset.key].type == 'CUSTOM'">
                <!-- 有子节点 -->
                <div v-if="sitset.children">

                  <div v-for="item in sitset.children" class="scene-item">
                    <div class="text-label" style="margin: 12px 0;">{{ item.name }}</div>
                    <n-checkbox-group style="margin-top: -12px"
                      v-model:value="(modal.form as any)[sitset.key][item.key]">
                      <NCheckbox style="min-width: 100px;margin-top: 12px;" v-for="(scene) in item.optional"
                        :value="'' + scene?.id">{{
                          scene?.description }}</NCheckbox>
                    </n-checkbox-group>
                  </div>
                </div>
                <div v-else>

                  <n-checkbox-group style="margin-top: -12px" v-model:value="(modal.form as any)[sitset.key].value">
                    <NCheckbox style="min-width: 100px;margin-top: 12px;" :value="'' + scene.id"
                      v-for="scene in sitset.optional">{{
                        scene.description }}</NCheckbox>
                  </n-checkbox-group>
                </div>
              </div>
            </div>
          </n-form-item>
          <n-form-item label="优量汇智能场景匹配" path="title" v-if="siteSet.includes(15)">
            <n-switch v-model:value="position.scene_spec.flow_optimization_enabled" :checked-value="1"
              :unchecked-value="0"></n-switch>
          </n-form-item>
        </x-form>
      </n-scrollbar>
      <template #footer>
        <div class="text-right">
          <n-button type="primary" @click="closeModal">确认</n-button>
        </div>
      </template>
    </n-modal>
  </n-card>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
const route = useRoute()
import { XForm } from '@/components'
import { NEmpty, NSkeleton, NCard, NFormItem, NRadioGroup, NRadioButton, useMessage, NModal, NRadio, NCheckboxGroup, NCheckbox, NScrollbar, NButton, NSwitch } from 'naive-ui'
import { computed, onMounted, reactive, ref, watch } from 'vue';
import Position from '@/store/modules/adv/position';
import { getAdvSiteset, getAdvSceneSpecTags } from '@/api/intelligent';
import { useStore } from '@/store'
import PositionSummary from '@/views/advertising/ads/create/components/PositionSummary.vue'
const store = useStore()
const message = useMessage();
defineProps({
  index: {
    type: Number
  }
})


const adv = computed(() => {
  return store.state.adv.modal
});
const creativor = computed(() => {
  return adv.value.creativor;
});
const diect = computed(() => store.state.adv.modal.diect);
const position = computed(() => {
  return store.state.adv.modal.position
})
const accounts = computed(() => {
  return store.state.adv.accounts;

})


const account = computed(() => {
  const accounts = store.state.adv.accounts;
  return accounts[0];
})

const market = computed(() => {
  const market = store.state.adv.modal.market;
  return market;
})





const sitsetAutomaticModal = reactive([{
  name: '微信公众号与小程序定投',
  code: 'WECHAT_POSITION',
  optional: [],
  key: 'wechat_position',
  endKey: 'wechatPosition',
  // 后端query
  // 微信公众号与小程序
  // 支持的版位
  supportSitSet: [21, 116],
},
{
  key: 'wechat_channels_scene',
  name: '微信视频号定投',
  endKey: 'wechatChannelsScene',
  code: 'WECHAT_CHANNELS_SCENE',
  supportSitSet: [113],
  optional: []
},
{
  name: '微信公众号与小程序场景',
  key: 'wechat_scene',
  endKey: '',
  supportSitSet: [21, 116],
  code: '-1',
  children: [{
    name: '公众号媒体类型',
    key: 'official_account_media_category',
    code: 'OFFICIAL_ACCOUNT_MEDIA_CATEGORY',
    endKey: 'officialAccountMediaCategory',
    optional: []
  }, {
    name: '小程序小游戏流量类型',
    key: 'mini_program_and_mini_game',
    code: 'MINI_PROGRAM_AND_MINI_GAME',
    endKey: 'miniProgramAndMiniGame',
    optional: []
  }, {
    name: '订单详情页消费场景',
    code: 'PAY_SCENE',
    endKey: 'payScene',
    key: 'pay_scene',
    optional: []
  }]
}, {
  name: '优量汇广告展示场景',
  // 优量汇
  supportSitSet: [15],
  optional: [],
  key: 'mobile_union_category',
  code: 'MOBILE_UNION_CATEGORY',
  endKey: 'mobileUnionCategory',
}]);

const sitsetAutomaticRuleModal = computed(() => {
  const siteSet = position.value.siteSet;
  if (position.value.isAutoSiteSet) return sitsetAutomaticModal;
  return sitsetAutomaticModal.filter(_ => !!_.supportSitSet.find(id => siteSet.includes(id)));
})

// function

async function changeSceneCustome(siteset: any, action: string) {
  if (!account.value) return;
  if (action === 'NONE') return;
  if (siteset.children) {
    siteset.children.map((sit: any) => {
      if (sit.optional.length) return;
      getAdvSceneSpecTags({
        accountCode: account.value.accountCode,
        type: sit.code
      }).then(res => {
        sit.optional = [].concat([], res.data);
      })
    })
  } else {
    if (siteset.optional.length) return;
    getAdvSceneSpecTags({
      accountCode: account.value.accountCode,
      type: siteset.code
    }).then(res => {
      siteset.optional = [].concat([], res.data);
    })
  }

}

async function changeSiteType(v) {
  if(v === 1) {
    position.value.siteSet = [122];
  }else {
    position.value.siteSet = [113, 122];
  }
  await store.dispatch('adv/getCreativeTemplateList');
  store.commit('adv/SET_NORMAL_CREATIVE')

}






const modal = reactive({
  show: false,
  form: position.value.scene_spec
});
function closeModal() {
  modal.show = false;
  store.commit('adv/UPDATE_POSITION_SCENE_SPEC', modal.form)
}



// 返显

function getBackDisplay() {
  const specTagQuerysFetch: any = [];
  modal.form = position.value.scene_spec;
  Object.keys(modal.form).map(key => {
    const value = (modal.form as any)[key];
    if (value.type === 'CUSTOM') {
      const sitsetModal = sitsetAutomaticModal.find((_: any) => _.key == key);
      if (sitsetModal) {
        sitsetModal.children ? sitsetModal.children.map((item: any) => {
          function fetch() {
            getAdvSceneSpecTags({
              accountCode: account.value.accountCode,
              type: item.code
            }).then(res => {
              item.optional = [].concat([], res.data);
            });
          }
          specTagQuerysFetch.push(fetch)
        }) : (
          specTagQuerysFetch.push(function () {
            getAdvSceneSpecTags({
              accountCode: account.value.accountCode,
              type: sitsetModal.code
            }).then(res => {
              sitsetModal.optional = [].concat([], res.data);
            });

          })
        )
      }
    }
  });
  setSiteName(position.value.siteSet);
  // console.log('jjj', specTagQuerysFetch);
  specTagQuerysFetch.map((_: any) => _())

}

async function onSitesitUpdate(value: any) {
  setSiteName(value);
  // 如果是视频号
  if (adv.value.isOnlyWxChannels) {
    store.commit('adv/UPDATE_ADV_TARGET_VALUE', {
      path: ['creativor'],
      key: 'brandType',
      value: 'WECHAT_CHANNELS'
    })
  }
  formatTreeList.value.map(({ id }: any) => {
    if (isSiteSetDisabled(id)) {
      const i = siteSet.value.findIndex(site => site == id);
      i > -1 && siteSet.value.splice(i, 1);
    }
  });
  adv.value.schedulePrice.deepConversionGoal = undefined;
  // 选中会清空
  diect.value.targeting.geo_location.location_types = ["LIVE_IN"];
  store.commit('adv/CONTROL_MODULE_INFOUPDATE_ACTION', {
    name: 'diect'
  });
  await store.dispatch('adv/getCreativeTemplateList');
  store.commit('adv/SET_NORMAL_CREATIVE')

}

function handleModalShow() {
  modal.show = true;
}
// 单选与多选
const select = ref({
  checkbox: [],
  radio: []
})
const treeList = ref();

function isSiteSetDisabled(key: any) {
  // 选择视频号
  if (market.value.marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_CHANNELS_LIVE') {
    // 选择了微信视频号 微信朋友圈[102] + 微信公众号与小程序-3000 = [21, 116,]   + 微信视频号[113]  可选
    if (siteSet.value.includes(113)) return ![102, -3000, 113].includes(key);
    // 选择了微信公众号与小程序
    if (siteSet.value.includes(21) || siteSet.value.includes(116)) return ![102, -3000].includes(key);
    // 选择了腾讯平台与内容媒体
    if (siteSet.value.includes(1)) return ![102, -3000, 1].includes(key);
    // 选择了优量汇
    if (siteSet.value.includes(15)) return ![102, -3000, 15].includes(key);
    return false;
  }
  return false;
}
// 格式化数据
const formatTreeList = computed(() => {
  if (position.value.isAutoSiteSet) return treeList.value.filter(_ => _.id == 122);
  return treeList.value
})


const siteSet = computed(() => {
  return position.value.siteSet
})

onMounted(() => {
  getSiteSet('')
})
async function getSiteSet(status: string) {
  store.commit('adv/TRIGGER_MODULE_LOADING', {
    name: 'position'
  })

  if (!treeList.value) {
    getAdvSiteset({
      marketingTargetType: adv.value.market.marketingTargetType
    }).then(res => {
      treeList.value = res.data;
      setSelect(treeList.value);
      store.commit('adv/TRIGGER_MODULE_LOADING', {
        name: 'position'
      })

    })

  }
}
// 递归处理单选与多选数据
function setSelect(list: any[]) {
  list.forEach((item: any) => {
    if (item.children) {
      setSelect(item.children)
    }
    if (item.multiSelect) {
      (select.value.checkbox as any).push(item.id)
    } else {
      (select.value.radio as any).push(item.id)
    }
  })
}
// 设置
function setSiteName(site: any) {

  const positionName = position.value.siteSetType == 1 ? '自动版位' : getSiteName(treeList.value, site).join('、');
  store.commit('adv/UPDATE_POSITION_INFO', {
    name: positionName
  })
}
function getSiteName(list: any[], site: any[]) {
  const arr: any[] = []
  list
    ? list.forEach((item) => {
      if (item.children && item.children.length > 0) {
        // 仅展示一级名称，不去遍历子级名称，否则名称长度过长
        if (
          item.children.some((t) => {
            return site.some((s) => s === t.id)
          })
        ) {
          arr.push(item.name)
        }
      } else {
        if (site.some((s) => s === item.id)) {
          arr.push(item.name)
        }
      }
    })
    : null
  return arr
}
// 供父级调用，进行校验与数据拼接返回
async function fetchFormData() {
  const params = {
    // siteSetPackage: select.value,
    siteSet: JSON.stringify(position.value.siteSet)
  }
  return params
}
async function defaultAction() {

  if (!creativor.value.creativeTemplateId) {
    await store.dispatch('adv/getCreativeTemplateList');
    store.commit('adv/SET_NORMAL_CREATIVE')
  }

}

defineExpose({
  defaultAction,
  fetchFormData,
  getBackDisplay
})
</script>

<style lang="scss"></style>
<style scoped lang="scss">
.scene-custom-container {
  .scene-item+.scene-item {
    margin-top: 12px;
  }

}
</style>
